import datetime
import json
from http.server import BaseHTTPRequestHandler, HTTPServer

from DrissionPage._configs.chromium_options import ChromiumOptions
from DrissionPage._pages.chromium_page import ChromiumPage

data = []
"""
使用服务器方式传递操作数据
这种方式需要禁止浏览器的跨域请求
"""

# 自定义请求处理类
class Server(BaseHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    # 处理 POST 请求
    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length).decode('utf-8')
        post_data_dict = json.loads(post_data)
        print(post_data)
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()

        response_data = {'message': 'Data received successfully', 'data_received': post_data_dict}
        self.wfile.write(json.dumps(response_data).encode('utf-8'))
        data.append(post_data_dict)
        record_data()

    @staticmethod
    def start_server():
        host = '127.0.0.1'
        port = 8000
        # 启动服务器
        server = HTTPServer((host, port), Server)
        # 定义服务器地址和端口
        print('服务器运行在 http://{}:{}/'.format(host, port))
        # 保持服务器持续运行
        server.serve_forever()

    @staticmethod
    def init():
        co = ChromiumOptions()
        co.set_argument('--disable-web-security')
        page = ChromiumPage(co)
        with open('click.js', 'r', encoding='utf-8') as file:
            js = file.read()
        page.add_init_js(js)
        page.get("https://www.baidu.com")
        Server.start_server()


def record_data():
    with open(filepath, 'w+') as file:
        json.dump(data, file)


class Manager:
    def __init__(self):
        self.init_page()
        self.init_server()
        self.filename = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')

    def init_server(self):
        self._host = '127.0.0.1'
        self._port = 8000
        self._server = HTTPServer((self._host, self._port), Server)
        # 定义服务器地址和端口
        print('服务器运行在 http://{}:{}/'.format(self._host, self._port))
        # 保持服务器持续运行
        self._server.serve_forever()

    def init_page(self):
        co = ChromiumOptions()
        co.set_argument('--disable-web-security')
        self.page = ChromiumPage(co)
        with open('click.js', 'r', encoding='utf-8') as file:
            js = file.read()
        self.page.add_init_js(js)
        self.page.get("https://www.baidu.com")


if __name__ == '__main__':
    filepath = f"record_list/{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.json"
    manager = Manager()
